<template>
  <div class="main">
    <div
      v-bind:class="{
        isMobile: mobileFlag,
        notMobile: !mobileFlag,
        containers: !mobileFlag,
        mobileContainers: mobileFlag,
      }"
    >
      <div class="main-top">
        <div  style="width: 30%; color: #6c848e;font-size: 0.8em; margin-left:5%">
          <div>截 止 时 间 :</div>
          <div>{{ this.endTime}}</div>
        </div>
        <div style="flex: 1; text-align: center">
          <div
            style="
              margin-left: 15px;
              font-size: 1.2em;
              word-wrap: break-word;
              width: 60%;
              text-align: center;
            "
          >
            {{ this.title }}
          </div>
          <div
            style="
              width: 60%;
              word-wrap: break-word;
              margin-left: 15px;
              font-size: 0.8em;
              margin-top: 5px;
              color: #6c848e;
              text-align: center;
            "
          >
            {{ this.description }}
          </div>
        </div>
        <div>
          <div
            style="
              font-size: 2.5em;
              color: #409eff;
              width: 2em;
              font-style: italic;
              width: 150px;
              text-align: center;
            "
          >
            {{ this.getPaperScore() }}
          </div>
        </div>
      </div>
      <el-divider></el-divider>
      <el-card
        class="box-card"
        v-for="(question, index) in questionList"
        :key="index"
        style="margin-top: 10px"
      >
        <div style="display: flex; margin-left: 20px">
          <div style="color: #409eff; margin-bottom: 8px; font-size: 18px">
            <div v-if="question.questionType == 'radio'" style="width: 90px">
              {{ index + 1 + ". " + "单选题" }}
            </div>
            <div v-if="question.questionType == 'checkbox'" style="width: 90px">
              {{ index + 1 + ". " + "多选题" }}
            </div>
            <div v-if="question.questionType == 'judge'" style="width: 90px">
              {{ index + 1 + ". " + "判断题" }}
            </div>
            <div v-if="question.questionType == 'text'" style="width: 90px">
              {{ index + 1 + ". " + "填空题" }}
            </div>
            <div v-if="question.questionType == 'texts'" style="width: 90px">
              {{ index + 1 + ". " + "简答题" }}
            </div>
          </div>
          <div style="flex: 1"></div>
          <div style="color: #ffcd41; width: 120px; margin-right: 10%">
            {{ "（分值：" + question.score + "）" }}
          </div>
        </div>
        <div style="font-size: 15px; margin-left: 2em">
          {{ question.content }}
        </div>

        <!-- 单选题 -->
        <el-radio-group
          v-if="question.questionType == 'radio'"
          style="margin-left: 20px"
          v-model="question.radioValue"
        >
          <!-- <span>{{ index + 1 + "." }}</span> -->
          <div v-for="(option, index) in question.choiceList" :key="index">
            <el-radio
              :label="option.id"
              style="margin-top: 10px; margin-left: 1em"
              >{{ question.choiceList[index].content }}
            </el-radio>
          </div>
        </el-radio-group>

        <!-- 多选题 -->
        <el-checkbox-group
          v-if="question.questionType == 'checkbox'"
          style="margin-left: 20px"
          v-model="question.checkboxValue"
        >
          <!-- <span>{{ index + 1 + "." }}</span> -->
          <div v-for="(option, index) in question.choiceList" :key="index">
            <el-checkbox
              :label="option.id"
              style="margin-top: 10px; margin-left: 1em"
              >{{ question.choiceList[index].content }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
        <!-- 判断题 -->
        <div
          v-if="question.questionType == 'judge'"
          style="margin-top: 10px; margin-left: 2em"
        >
          <el-radio-group v-model="question.judgeValue">
            <el-radio :label="'yes'">正确 </el-radio>
            <el-radio :label="'no'" style="margin-left: 10px"> 错误</el-radio>
          </el-radio-group>
        </div>

        <!-- 填空题 -->
        <div
          v-if="question.questionType == 'text'"
          v-for="(text, index) in question.rowNum"
          :key="index"
          style="margin-left: 2em"
        >
          <el-input
            v-model="question.amazingValue.textValue[index]"
            style="margin-top: 10px"
          ></el-input>
        </div>

        <!-- 简答题 -->
        <div v-if="question.questionType == 'texts'" style="margin-left: 2em">
          <el-input
            type="textarea"
            :rows="question.rowNum"
            v-model="question.textsValue"
            style="margin-top: 10px"
          >
          </el-input>
        </div>
      </el-card>
      <div style="width: 100%; margin-bottom: 8px; margin-top: 20px">
        <el-button
          type="primary"
          plain
          style="margin-left: 50%"
          @click="justSave()"
          >保 存</el-button
        >
        <el-button
          type="primary"
          plain
          style="margin-left: 5%"
          @click="submitAnswer()"
          >提 交</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
let _ = require("lodash");
export default {
  data() {
    return {
      id: -1,
      userId: null,
      mobileFlag: false,
      questionAnswerList: [],
      title: "标题",
      description: "描述",
      answerId: null,
      questionList: [],
      paperScore: "",
      questionCount: "",
      endTime:"",
    };
  },
  computed: {
    // surplusTime: function () {
    //   return this.times( new Date(this.endTime).getTime()-new Date().getTime());
    // },

    getAnswer: function () {
      let answer = {};
      let user = JSON.parse(sessionStorage.getItem("user"));
      //answer.username = user.username;
      answer.realName = user.realName;
      answer.examPaperId = this.id;
      answer.id = this.answerId;
      answer.paperName = this.title;
      answer.paperScore = this.paperScore;
      answer.questionCount = this.questionCount;
      answer.userId = sessionStorage.getItem("id");
      //answer.userName = sessionStorage.getItem("userName");
      let questionAnswerList = [];
      questionAnswerList.examPaperId = this.id;

      this.questionList.forEach((question) => {
        let questionAnswer = {};
        questionAnswer.id = question.answerQuestionId;
        questionAnswer.questionId = question.id;
        questionAnswer.questionScore = question.score;
        questionAnswer.examPaperId = this.id;
        questionAnswer.questionType = question.questionType;
        questionAnswer.userId = sessionStorage.getItem("id");
        if (question.questionType == "radio") {
          questionAnswer.userAnswer = question.radioValue;
        } else if (question.questionType == "checkbox") {
          questionAnswer.userAnswer = question.checkboxValue.join("_");
        } else if (question.questionType == "judge") {
          // if(question.judgeValue == "正确"){
          //   question.judgeValue = "yes"
          // }else if(question.judgeValue == "错误"){
          //   question.judgeValue = "no"
          // }else{

          // }

          questionAnswer.userAnswer = question.judgeValue;
        } else if (question.questionType == "text") {
          questionAnswer.userAnswer = question.amazingValue.textValue.join("_");
        } else {
          questionAnswer.userAnswer = question.textsValue;
        }

        questionAnswerList.push(questionAnswer);
      });
      answer.questionAnswerList = questionAnswerList;
      return answer;
    },
    update: function () {
      let questionAnswerList = [];
      this.questionList.forEach((question) => {
        let questionAnswer = {};

        if (question.questionType == "radio") {
          questionAnswer.userAnswer = question.radioValue;
        } else if (question.questionType == "checkbox") {
          questionAnswer.userAnswer = question.checkboxValue.join("_");
        } else if (question.questionType == "judge") {
          // if(question.judgeValue == "正确"){
          //   question.judgeValue = "yes"
          // }else if(question.judgeValue == "错误"){
          //   question.judgeValue = "no"
          // }else{

          // }

          questionAnswer.userAnswer = question.judgeValue;
        } else if (question.questionType == "text") {
          questionAnswer.userAnswer = question.amazingValue.textValue.join("_");
        } else {
          questionAnswer.userAnswer = question.textsValue;
        }

        questionAnswerList.push(questionAnswer);
      });
      return questionAnswerList;
    },
  },
  watch: {
    update: function () {
      this.saveAnswer();
      console.log(this.getAnswer);
    },
  },
  methods: {
    times(data) {
　　var time = Number(data);
　　var h = Math.floor(time / 3600);
　　var m = Math.floor((time % 3600) / 60);
　　var s = parseInt(time % 3600) % 60;
　　var hh = h < 10 ? "0" + h : h;
　　var mm = m < 10 ? "0" + m : m;
　　var ss = s < 10 ? "0" + s : s;
　　return hh + ":" + mm + ":" + ss;
},
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString(), // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
          );
        }
      }
      return fmt;
    },
    getPaperScore() {
      let paperScore = 0;
      this.questionList.forEach((question) => {
        paperScore = paperScore + question.score;
      });
      return paperScore;
    },
    justSave() {
      this.$message({
        message: "保 存 成 功",
        type: "success",
      });
    },
    saveAnswer: _.debounce(function () {
      let datas = this.getAnswer;
      console.log("qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
      console.log(this.getAnswer);
      const _this = this;
      axios({
        method: "post",
        url: _this.APIurl.apiUrl.domainName + "examPaperAnswer/save",
        headers: {
          "Content-Type": "application/json",
        },
        data: datas,
      }).then(function (response) {
        if (response.data.code == 1) {
          _this.answerId = response.data.data.id;
          console.log(
            "ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss"
          );
          console.log(response.data.data.questionAnswerList);
          _this.questionList.forEach(function (question, index) {
            question.answerQuestionId =
              response.data.data.questionAnswerList[index].id;
            console.log(question.answerQuestionId);
          });
        }
      });
      this.$message({
        message: "已 自 动 保 存",
        duration:1000,
        type: "success",
      });
    }, 2000),

    submitAnswer() {
      let datas = this.getAnswer;
      datas.finishStatus = true;
      console.log(this.getAnswer);
      const _this = this;
      axios({
        method: "post",
        url: _this.APIurl.apiUrl.domainName + "examPaperAnswer/save",
        headers: {
          "Content-Type": "application/json",
        },
        data: datas,
      });
      this.$router.push({ path: "/finish", query: { commitFlag: true } });
    },
  },
  created() {
    this.id = this.$route.params.id;
    console.log(this.id);
    const _this = this;
    this.userId = sessionStorage.getItem("id");

    axios
      .get(
        _this.APIurl.apiUrl.domainName +
          "examPaper/fill/" +
          _this.userId +
          "/" +
          _this.id
      )
      .then(function (response) {
        if (response.data.code == 0) {
          _this.$router.push({
            path: "/finish",
            query: {
              msg: response.data.msg,
              answerFlag: true,
            },
          });
        }

        _this.title = response.data.data.title;
        _this.endTime = response.data.data.endTime;

        _this.description = response.data.data.description;
        _this.questionList = response.data.data.questionList;
        _this.paperScore = _this.getPaperScore();
        _this.questionCount = response.data.data.questionCount;

        for (let i = 0; i < _this.questionList.length; i++) {
          let rowNum = _this.questionList[i].rowNum;
          let textValue = new Array(rowNum);
          let amazing = { textValue: textValue };

          // if(_this.questionList[i].textsValue=undefined){
          //    _this.$set(_this.questionList[i], "textsValue", "");
          // }else if(_this.questionList[i].checkboxValue=undefined){

          // }else if(_this.questionList[i].amazingValue=undefined){

          // }else if(_this.questionList[i].judgeValue=undefined){

          // }else if(_this.questionList[i].radioValue=undefined){

          // }

          _this.$set(_this.questionList[i], "textsValue", "");
          _this.$set(_this.questionList[i], "radioValue", -1);
          _this.$set(_this.questionList[i], "checkboxValue", []);
          _this.$set(_this.questionList[i], "amazingValue", amazing);
          _this.$set(_this.questionList[i], "judgeValue", -1);
        }
      })
      .then(function () {
        axios
          .get(
            _this.APIurl.apiUrl.domainName +
              "examPaperAnswer/findByUserIdAndPaperId/" +
              _this.userId +
              "/" +
              _this.id
          )
          .then(function (res) {
            if (res.data.data) {
              _this.answerId = res.data.data.id;

              _this.questionList.forEach(function (question, index) {
                if (question.questionType == "radio") {
                  _this.$set(
                    question,
                    "radioValue",
                    parseInt(res.data.data.questionAnswerList[index].userAnswer)
                  );
                  // question.radioValue =
                  //   res.data.data.questionAnswerList[index].userAnswer;
                } else if (question.questionType == "checkbox") {
                  let values = [];
                  res.data.data.questionAnswerList[index].userAnswer
                    .split("_")
                    .forEach(function (value) {
                      values.push(parseInt(value));
                    });

                  _this.$set(question, "checkboxValue", values);
                } else if (question.questionType == "judge") {
                  _this.$set(
                    question,
                    "judgeValue",
                    res.data.data.questionAnswerList[index].userAnswer
                  );
                } else if (question.questionType == "text") {
                  let rowNum = question.rowNum;
                  let textValue = new Array(rowNum);
                  let amazing = { textValue: textValue };
                  amazing.textValue =
                    res.data.data.questionAnswerList[index].userAnswer.split(
                      "_"
                    );
                  _this.$set(question, "amazingValue", amazing);
                } else {
                  _this.$set(
                    question,
                    "textsValue",
                    res.data.data.questionAnswerList[index].userAnswer
                  );
                }
              });
              _this.questionList.forEach(function (question, index) {
                question.answerQuestionId =
                  res.data.data.questionAnswerList[index].id;
              });
            }
          });
      });

    let flag = navigator.userAgent.match(
      /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
    );
    this.mobileFlag = flag;
    // this.questionList=sessionStorage.getItem('test');
    console.log(flag);
    console.log(this.mobileFlag);
  },
};
</script>

<style scoped>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.main {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}
.main-top {
  display: flex;
}
.flexs {
  display: flex;
  justify-content: center;
}
.isMobile {
  width: 100%;
  padding: 0px;
}
.notMobile {
  width: 70%;
}
.containers {
  border: 2px solid rgba(0, 0, 0, 0.12);
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 2%;
}
.mobile-containers {
  border: 2px solid rgba(0, 0, 0, 0.12);
  border-radius: 10px;
  padding: 0px;
  margin-bottom: 2%;
}
/* .main :first-child  /deep/ .el-card__body{
    padding-left: 0px;
    padding-right: 0px;
} */
</style>